package com.governtalk.backend.security;

import com.governtalk.backend.entity.User;
import com.governtalk.backend.repository.UserRepository;
// import io.jsonwebtoken.Claims;
// import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Autowired
    private UserRepository userRepository;
    
    // @Value("${jwt.secret}")
    // private String jwtSecret;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                  FilterChain filterChain) throws ServletException, IOException {
        
        // 跳过不需要认证的端点
        String requestURI = request.getRequestURI();
        System.out.println("JWT Filter processing URI: " + requestURI);
        if (requestURI.startsWith("/api/ai-solver/") || 
            requestURI.startsWith("/api/simple-login/") ||
            requestURI.startsWith("/api/test-auth/") ||
            requestURI.startsWith("/api/simple/") ||
            requestURI.startsWith("/api/password/")) {
            System.out.println("Skipping JWT filter for endpoint: " + requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        
        try {
            String token = getTokenFromRequest(request);
            
            if (token != null && validateToken(token)) {
                String username = getUsernameFromToken(token);
                
                if (username != null) {
                    User user = userRepository.findByUsername(username).orElse(null);
                    if (user != null) {
                        // 创建认证对象
                        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                        if (user.getRoles() != null) {
                            authorities = user.getRoles().stream()
                                    .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                                    .collect(Collectors.toList());
                        } else {
                            // 如果没有roles，设置默认的USER角色
                            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                        }
                        
                        UsernamePasswordAuthenticationToken auth = 
                            new UsernamePasswordAuthenticationToken(user.getUsername(), null, authorities);
                        SecurityContextHolder.getContext().setAuthentication(auth);
                    }
                }
            } else {
                // 如果没有token或token无效，设置默认的admin用户认证
                User adminUser = userRepository.findByUsername("admin").orElse(null);
                if (adminUser != null) {
                    List<SimpleGrantedAuthority> authorities = java.util.Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
                    UsernamePasswordAuthenticationToken auth = 
                        new UsernamePasswordAuthenticationToken("admin", null, authorities);
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            }
        } catch (Exception e) {
            // 如果出现异常，设置默认的admin用户认证
            try {
                User adminUser = userRepository.findByUsername("admin").orElse(null);
                if (adminUser != null) {
                    List<SimpleGrantedAuthority> authorities = java.util.Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
                    UsernamePasswordAuthenticationToken auth = 
                        new UsernamePasswordAuthenticationToken("admin", null, authorities);
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            } catch (Exception ex) {
                // 忽略异常，继续处理
            }
        }
        
        filterChain.doFilter(request, response);
    }
    
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
    
    private boolean validateToken(String token) {
        // 临时总是返回true
        return true;
    }
    
    private String getUsernameFromToken(String token) {
        // 临时返回简单用户名
        return "admin";
    }
}
